package com.phkj.qdh.ui.fragment.failover

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.com.cybertech.pdk.utils.GsonUtils
import com.chad.library.adapter4.QuickAdapterHelper
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.lxj.xpopup.XPopup
import com.phkj.qdh.R
import com.phkj.qdh.bean.FileUploadBean
import com.phkj.qdh.databinding.FragmentFailoverSubmitBinding
import com.phkj.qdh.net.FILE_UPLOAD
import com.phkj.qdh.bean.FailoverTypeBean
import com.phkj.qdh.bean.ZheDiThing
import com.phkj.qdh.net.msg
import com.phkj.qdh.ui.adapter.AddFileHeadAdapter
import com.phkj.qdh.ui.adapter.FailoverThingsShowAdapter
import com.phkj.qdh.ui.adapter.FileTitleAdapter
import com.phkj.qdh.ui.adapter.ImageChangeAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAddAdapter
import com.phkj.qdh.ui.adapter.UploadFileBean
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.dialog.FailoverReduceTypeListener
import com.phkj.qdh.ui.dialog.FileoverReduceTypeSelectDialog
import com.phkj.qdh.ui.fragment.myfailover.MyFailoverBaseDetailFragment
import com.phkj.qdh.ui.fragment.myfailover.MyFailoverTeamDetailFragment
import com.phkj.qdh.utils.FileHelper
import com.phkj.qdh.utils.FileUtils
import com.phkj.qdh.utils.GetImgContract
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.TakePhoto
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.requestMain
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import rxhttp3.RxHttp
import rxhttp3.toFlowResponse
import java.io.File
import java.text.SimpleDateFormat
import java.util.GregorianCalendar
import java.util.HashMap
import java.util.Locale

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 容错激励提交
 */
class FailoverSubmitFragment : Fragment() {
    private var param1: FailoverTypeBean? = null
    private var param2: String? = null
    private var _binding: FragmentFailoverSubmitBinding? = null
    private val binding get() = _binding!!
    private val iVAdapter by lazy { ImageChangeAdapter(false) }
    private val fileTitleAdapter by lazy { FileTitleAdapter() }
    private val iVAddAdapter by lazy { ImagerViewAddAdapter() }
    private val addFileHeadAdapter by lazy { AddFileHeadAdapter() }
    private val failoverThingsShowAdapter by lazy { FailoverThingsShowAdapter() }
    private lateinit var vm: FailoverVM
    private var imageUri: Uri? = null
    private var eventType: Int? = null
    private var inspectTypeId: Int? = null
    private var isReplace: Boolean = false
    private var replacePos: Int? = null
    private var filePath: String = ""
    private val takePic =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { boolean ->
            if (boolean) {
                try {
                    imageUri?.let { uri ->
                        val option = BitmapFactory.Options()
                        option.inPreferredConfig = Bitmap.Config.RGB_565
                        val bitmap = BitmapFactory.decodeStream(
                            requireContext().contentResolver.openInputStream(uri), null, option
                        )
                        val yasuohou = TakePhoto.scaleBitmap(bitmap, 0.5f)
                        val path = TakePhoto.saveBitmap2File(yasuohou)
                        uploadImg(path)
                    }

                } catch (e: Exception) {

                }
            }
        }
    private val selectImg = registerForActivityResult(GetImgContract()) { uri ->
        uri?.let {
            LogUtil.E(it.toString())
            val file = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadImg(file)
        }
    }

    private val getFile = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.let { it1 ->
            val filePath = FileHelper.getFileAbsolutePath(requireContext(), it)
            uploadFile(filePath)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getParcelable(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })


        parentFragmentManager.setFragmentResultListener("key", this) { req, bundle ->
            val data = bundle.getParcelableArrayList<ZheDiThing>("data")
            failoverThingsShowAdapter.submitList(data)
        }


    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentFailoverSubmitBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getFailoverVMProvider())[FailoverVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (param1 == null) {
            LogUtil.E("isNull")
            parentFragmentManager.popBackStack()
            return
        }
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            tvType.text = param1!!.name
            llFailoverThings.setOnClickListener {
                eventType?.let { s ->
                    inspectTypeId?.let { a ->
                        parentFragmentManager.commit {
                            add(id, FailoverThingSelectFragment.newInstance(s, a))
                            addToBackStack("things")
                        }
                    }

                }
            }
            rvShow.run {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = failoverThingsShowAdapter
                addItemDecoration(
                    MyItemDecoration(
                        width = 2
                    )
                )
            }
            rvPic.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }
            rvFile.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(requireContext(), R.color.transparent),
                        28,
                        RecyclerView.HORIZONTAL
                    )
                )
            }
            llZhedileixin.setOnClickListener {//折抵类型
                getFailoverReduceType()
            }
            btn.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("提交", "确定要提交吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        saveFilover()
                    }

                    override fun dCancel() {

                    }
                })
                dialog.show(parentFragmentManager, "")
            }
            tvDarft.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("保存草稿", "确定要保存草稿吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        saveFilover(0)
                    }

                    override fun dCancel() {

                    }
                })
                dialog.show(parentFragmentManager, "")
            }

        }
        failoverThingsShowAdapter.addOnItemChildClickListener(R.id.tv_Detail) { adapter, _, pos ->
            val data = adapter.getItem(pos)
            when (data?.eventType) {
                0 -> {
                    parentFragmentManager.commit {
                        addToBackStack("fail")
                        add(id, MyFailoverTeamDetailFragment.newInstance(data.id, ""))
                        setReorderingAllowed(true)
                    }
                }

                1 -> {//基础巡查
                    parentFragmentManager.commit {
                        addToBackStack("fail")
                        add(id, MyFailoverBaseDetailFragment.newInstance(data!!.id, ""))
                        setReorderingAllowed(true)
                    }
                }
            }
        }
        val fileHelper = QuickAdapterHelper.Builder(fileTitleAdapter).build()
        fileHelper.addBeforeAdapter(addFileHeadAdapter)
        addFileHeadAdapter.submitList(arrayListOf("s"))
        binding.rvFile.adapter = fileHelper.adapter
        addFileHeadAdapter.setOnItemClickListener { _, _, _ ->
            if (fileTitleAdapter.items.size >= 6) {
                return@setOnItemClickListener
            }
            getFile.launch("application/msword")
        }

        val helper = QuickAdapterHelper.Builder(iVAdapter).build()
        helper.addBeforeAdapter(iVAddAdapter)
        iVAddAdapter.submitList(arrayListOf("s"))
        binding.rvPic.adapter = helper.adapter

        iVAdapter.addOnItemChildClickListener(R.id.iv_delete) { adapter, _, pos ->
            replacePos = pos
            isReplace = true
            val dialog = CommonConfirmDialog.getInstance(
                "替换", "替换方式", "选择照片", "拍照"
            )
            dialog.setCancelListener(object : CommonConfirmListener {
                override fun dOk() {
                    selectImg.launch(null)
                }

                override fun dCancel() {
                    takePhoto()
                }

            })
            dialog.show(parentFragmentManager, "")
        }

        iVAddAdapter.setOnItemClickListener { adapter, data, pos ->
            isReplace = false
            replacePos = null
            if (iVAdapter.items.size >= 6) {
                ToastUtils.show("图片数量不能超过6张")
                return@setOnItemClickListener
            }
            XXPermissions.with(requireContext())
                .permission(arrayListOf(Permission.READ_MEDIA_IMAGES, Permission.CAMERA))
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            val dialog = CommonConfirmDialog.getInstance(
                                "上传图片", "请选择上传方式", "选择照片", "拍照"
                            )
                            dialog.setCancelListener(object : CommonConfirmListener {
                                override fun dOk() {
                                    selectImg.launch(null)
                                }

                                override fun dCancel() {
                                    takePhoto()
                                }

                            })
                            dialog.show(parentFragmentManager, "")
                        }
                    }

                    override fun onDenied(
                        permissions: MutableList<String>, doNotAskAgain: Boolean
                    ) {
                        super.onDenied(permissions, doNotAskAgain)
                    }
                })
        }

        launchAndRepeatWithViewLifecycle {
            vm.failoverReduceTypeList.collectLatest {
                val dialog = FileoverReduceTypeSelectDialog(requireContext(), it)
                dialog.setListener(object : FailoverReduceTypeListener {
                    override fun ok(id: Int, parentId: Int, name: String, i: Int?) {
                        inspectTypeId = id
                        binding.tvType1.text = name
                        eventType = i
                        failoverThingsShowAdapter.submitList(null)
                        LogUtil.E("$id    $eventType")
                    }

                })
                XPopup.Builder(requireContext()).asCustom(dialog).show()
            }
        }
        launchAndRepeatWithViewLifecycle {
            vm.failoverSaveResult.collectLatest {
                if (it == 0) {
                    ToastUtils.show("提交成功")
                    parentFragmentManager.popBackStack(
                        "fail", FragmentManager.POP_BACK_STACK_INCLUSIVE
                    )
                }
            }
        }
    }

    private fun getFailoverReduceType() {
        vm.getFailoverReduceType()
    }

    private fun saveFilover(isDrafts: Int? = null) {
        if (binding.tvType1.text.isNullOrBlank()) {
            ToastUtils.show("请选择折抵类型")
            return
        }

        if (failoverThingsShowAdapter.items.isEmpty()) {
            ToastUtils.show("请选择折抵事项")
            return
        }

        if (binding.edtReson.text.isNullOrBlank()) {
            ToastUtils.show("请输入折抵理由")
            return
        }
        if (iVAdapter.items.isEmpty()) {
            ToastUtils.show("请上传图片")
            return
        }
        if (fileTitleAdapter.items.isEmpty()) {
            ToastUtils.show("请上传文件")
            return
        }
        val map = HashMap<String, Any?>()
        map["faultTolerantTypeId"] = param1?.id
        map["eventType"] = eventType
        map["eventTypeId"] = inspectTypeId
        map["eventId"] = failoverThingsShowAdapter.items.map { it.id }
        map["reason"] = binding.edtReson.text.toString()
        map["pictureList"] = iVAdapter.items
//        map["eventTypeId"] = eventType
        map["fileList"] = fileTitleAdapter.items.map { it1 -> it1.fileUrl }
        map["remark"] = binding.edtRemark.text.toString()
        map["isDrafts"] = isDrafts
        vm.saveFailover(map)
    }

    private fun takePhoto() {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        var outputImage = File(requireContext().externalCacheDir, fileName)
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        imageUri = if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                requireContext(), "com.phkj.qdh.fileprovider", outputImage
            )
        } else {
            Uri.fromFile(outputImage)
        }
        filePath = outputImage.absolutePath
        takePic.launch(imageUri)

    }

    private fun uploadImg(path: String) {
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", path).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(500)

                    if (isReplace) {
                        replacePos?.let { it1 -> iVAdapter.set(it1, it.url) }
                        isReplace = false
                        replacePos = null
                    } else {
                        iVAdapter.add(it.url)
                    }
                }
        }
    }


    private fun uploadFile(uri: String) {
        LogUtil.E("$uri")
        requestMain {
            RxHttp.postForm(FILE_UPLOAD).addFile("file", uri).toFlowResponse<FileUploadBean>()
                .catch { cause ->
                    ToastUtils.show(cause.msg)
                }.collectLatest {
                    delay(2000)
                    val name = uri.split("/")
                    fileTitleAdapter.add(UploadFileBean(name[name.size - 1], it.url))
                }
        }
    }

    companion object {
        /**
         *
         */
        @JvmStatic
        fun newInstance(param1: FailoverTypeBean, param2: String) = FailoverSubmitFragment().apply {
            arguments = Bundle().apply {
                putParcelable(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}